package com.zqh.web.interceptor;


import cn.hutool.core.util.ObjectUtil;
import com.zqh.web.annotation.AuthCheck;
import com.zqh.web.common.ErrorCode;
import com.zqh.web.common.login.LoginUser;
import com.zqh.web.common.login.LoginUserHolder;
import com.zqh.web.exception.BusinessException;
import com.zqh.web.model.enums.UserRoleEnum;
import jakarta.validation.constraints.NotNull;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class UserInterceptor {


    /**
     * 执行拦截
     *
     * @param joinPoint 切入点
     * @param authCheck 权限校验注解
     */
    @Around("@annotation(authCheck)")
    public Object doInterceptor(ProceedingJoinPoint joinPoint, @NotNull AuthCheck authCheck) throws Throwable {
        String mustRole = authCheck.mustRole();

        LoginUser loginUser =  LoginUserHolder.getLoginUser();

        // 未登录，拒绝
        if (ObjectUtil.isEmpty(loginUser)){
            throw new BusinessException(ErrorCode.ADMIN_LOGIN_AUTH);
        }

        UserRoleEnum mustRoleEnum = UserRoleEnum.getEnumByValue(mustRole);
        // 不需要权限，放行
        if (mustRoleEnum == null) {
            return joinPoint.proceed();
        }
        // 以下为：必须有该权限才通过
        // 获取当前用户具有的权限
        UserRoleEnum userRoleEnum = UserRoleEnum.getEnumByValue(loginUser.getUserRole());
        // 没有权限，拒绝
        if (userRoleEnum == null) {
            throw new BusinessException(ErrorCode.ADMIN_ACCESS_FORBIDDEN);
        }
        // 要求必须有管理员权限，但用户没有管理员权限，拒绝
        if (UserRoleEnum.ADMIN.equals(mustRoleEnum) && !UserRoleEnum.ADMIN.equals(userRoleEnum)) {
            throw new BusinessException(ErrorCode.ADMIN_ACCESS_FORBIDDEN);
        }
        // 通过权限校验，放行
        return joinPoint.proceed();
    }

}

